package com.pap.oauth.config;

import com.pap.base.constant.JWTConstants;
import com.pap.oauth.config.exception.oauth.PapSecurityOauth2WebResponseExceptionTranslator;
import com.pap.oauth.config.security.PapUserDetailsService;
import com.pap.oauth.config.security.jwt.convert.PapDefaultAccessTokenConverter;
import com.pap.oauth.config.security.jwt.convert.PapDefaultUserAuthenticationConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

import java.util.Arrays;

@Configuration
@EnableAuthorizationServer //提供/oauth/authorize,/oauth/token,/oauth/check_token,/oauth/confirm_access,/oauth/error
public class OAuth2Config extends AuthorizationServerConfigurerAdapter {

     /**
     *  @Deprecated 取消自定义的 userDetailsService， 而改为在 PapUserDetailsAuthenticationProvider 中的支持。
     */
//    @Autowired
//    private PapUserDetailsService userDetailsService;

    /**
     * 自定义异常转换器
     */
    @Autowired
    private PapSecurityOauth2WebResponseExceptionTranslator papSecurityOauth2WebResponseExceptionTranslator;

    /**
     * 注入authenticationManager
     * 来支持 password grant type
     */
    @Autowired
    private AuthenticationManager authenticationManager;

    // add begin

    @Autowired
    private ClientDetailsService clientDetailsService;

    @Bean
    @Primary
    public AuthorizationServerTokenServices tokenService() {
        DefaultTokenServices service=new DefaultTokenServices();
        service.setClientDetailsService(clientDetailsService);
        service.setSupportRefreshToken(true);
        service.setTokenStore(tokenStore());

        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(jwtAccessTokenConverter()));
        service.setTokenEnhancer(tokenEnhancerChain);

        service.setAccessTokenValiditySeconds(7200); // 令牌默认有效期2小时
        service.setRefreshTokenValiditySeconds(259200); // 刷新令牌默认有效期3天
        return service;
    }

    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(jwtAccessTokenConverter());
    }

    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
        jwtAccessTokenConverter.setSigningKey(JWTConstants.SECRET);

        // TODO 如下两行代码，可以在此处增加 JWT 额外用户属性 。针对 accessTokenConverter 进行自定义扩充，增加属性。
        PapDefaultAccessTokenConverter papDefaultAccessTokenConverter = new PapDefaultAccessTokenConverter();
        PapDefaultUserAuthenticationConverter papDefaultUserAuthenticationConverter = new PapDefaultUserAuthenticationConverter();
        papDefaultAccessTokenConverter.setUserTokenConverter(papDefaultUserAuthenticationConverter);

        jwtAccessTokenConverter.setAccessTokenConverter(papDefaultAccessTokenConverter);

        return jwtAccessTokenConverter;
    }
    // add end

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                // .userDetailsService(userDetailsService)
                // 定制异常转换器
                .exceptionTranslator(papSecurityOauth2WebResponseExceptionTranslator)
                .authenticationManager(authenticationManager)
                .tokenServices(tokenService())
                ;
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security
                .tokenKeyAccess("permitAll()")
                .checkTokenAccess("isAuthenticated()");
    }


    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("pap")
                .secret("{noop}pap")
                .redirectUris("http://www.pap.com","http://www.baidu.com") //新增redirect_uri
                .authorizedGrantTypes("authorization_code", "client_credentials", "refresh_token",
                        "password", "implicit")
                .scopes("all")
                .resourceIds("pap")
                .accessTokenValiditySeconds(4800)
                .refreshTokenValiditySeconds(9600);
    }
}